package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.mapper.content.ActivityApplyMapper;
import com.example.everying.model.entity.chat.ChatConversationEntity;
import com.example.everying.model.entity.content.ActivityApply;
import com.example.everying.model.entity.content.ActivityArticle;
import com.example.everying.service.chat.ChatConversationService;
import com.example.everying.service.content.ActivityApplyService;
import com.example.everying.service.content.ActivityArticleService;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ApplyInfoMessageMessageHandler implements MessageHandler {

    private static ActivityApplyService activityApplyService;
    private static ActivityArticleService activityArticleService;
    private static ChatConversationService chatConversationService;

    private void setService(ActivityApplyService activityApplyService,
                            ActivityArticleService activityArticleService,
                            ChatConversationService chatConversationService) {
        ApplyInfoMessageMessageHandler.activityApplyService = activityApplyService;
        ApplyInfoMessageMessageHandler.activityArticleService = activityArticleService;
    }

    /**
     * @param session
     * @param message
     */
    @Override
    public void handle(Session session, JSONObject message) {
        String userId = WebSocketChatService.getUserId(session);
        String conversationId = message.getString("conversationId");
        String artId = message.getString("artId");

        QueryWrapper<ActivityApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("art_id", artId);
        queryWrapper.eq("user_id", userId);
        ActivityApply activityApply = activityApplyService.getOne(queryWrapper);
        if (activityApply == null) {
          log.info("没有申请该帖子的记录：{} ,用户id:{}",  artId,  userId);
          return;
        }

        JSONObject applyInfo = new JSONObject();
        applyInfo.put("type", "applyInfoMessage");
        applyInfo.put("applyInfo", activityApply);
        ChatConversationEntity conversation = chatConversationService.getById(conversationId);

        WebSocketChatService.sendMessageToUserId(conversation.getUser1Id(), applyInfo.toJSONString());
        WebSocketChatService.sendMessageToUserId(conversation.getUser2Id(), applyInfo.toJSONString());

    }
}
